package cn.zxl.spring.holiday.job.service.impl;

import cn.zxl.spring.holiday.job.domain.Employee;
import cn.zxl.spring.holiday.job.mapper.EmployeeMapper;
import cn.zxl.spring.holiday.job.mapper.RoleMapper;
import cn.zxl.spring.holiday.job.qo.QueryObject;
import cn.zxl.spring.holiday.job.service.EmployeeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bofeifei
 * @since 2021-10-01
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Employee> employees = employeeMapper.findAll(qo);
        return new PageInfo<>(employees);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteForEmployee(Long id) {
        employeeMapper.deleteById(id);
        roleMapper.removeEmpAndRol(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveEmpAndRol(Employee employee, Long[] roleIds) {
        employeeMapper.saveOne(employee);
        if (roleIds == null) {
            return;
        }
        roleMapper.saveEmpAndRol(employee.getId(),roleIds);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateEmpAndRol(Employee employee, Long[] roleIds) {
        employeeMapper.updateOne(employee);
        roleMapper.removeEmpAndRol(employee.getId());
        if (roleIds == null) {
            return;
        }
        roleMapper.saveEmpAndRol(employee.getId(),roleIds);
    }

    @Override
    public Employee findOne(Long id) {
        return employeeMapper.findOne(id);
    }

    @Override
    public Employee findByUsername(String username) {
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        return employeeMapper.selectOne(wrapper);
    }

    @Override
    public void batchInsert(List<Employee> employees) {
        employeeMapper.batchInsert(employees);
    }
}
